package com.gjw.springbucks.service;

import com.gjw.springbucks.model.Coffee;
import com.gjw.springbucks.model.CoffeeOrder;
import com.gjw.springbucks.model.OrderState;
import com.gjw.springbucks.repository.CoffeeOrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author Administrator
 * @since 2019/7/9.
 */
@Slf4j
@Service
@Transactional
public class CoffeeOrderService {

    @Autowired
    private CoffeeOrderRepository coffeeOrderRepository;

    public CoffeeOrder createOrder(String customer, Coffee... coffee) {
        CoffeeOrder coffeeOrder = CoffeeOrder.builder()
                .customer(customer)
                .items(new ArrayList<>(Arrays.asList(coffee)))
                .state(OrderState.INIT)
                .build();
        CoffeeOrder saved = coffeeOrderRepository.save(coffeeOrder);
        log.info("New Order:{}", saved);
        return saved;
    }

    public boolean updateState(CoffeeOrder coffeeOrder, OrderState orderState) {
        if (orderState.compareTo(coffeeOrder.getState()) <= 0) {
            log.warn("Wrong State order:{},{}", orderState, coffeeOrder.getState());
            return false;
        }

        coffeeOrder.setState(orderState);
        coffeeOrderRepository.save(coffeeOrder);
        log.info("Updated Order:{}", coffeeOrder);
        return true;
    }
}
